#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<cstring>
#include<string>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>



void Usage(std::string proc)
{
  std::cout<<"Usage: "<<proc<<"server_ip server_ port"<<std::endl;
}
// ./tcp_client server_ip server_port
int main(int argc,char* argv[])
{
  if(argc!=3)
  {
    Usage(argv[0]);
    return 1;
  }

  int sock = socket(AF_INET,SOCK_STREAM,0);
  struct sockaddr_in server;
  memset(&server,0,sizeof(server));
  server.sin_family = AF_INET;
  server.sin_port = htons(atoi(argv[2]));
  server.sin_addr.s_addr = inet_addr(argv[1]);

  //发起连接
  if(connect(sock,(struct sockaddr*)&server,sizeof(server))<0)
  {
    std::cerr<<"conncet err"<<std::endl;
    return 3;
  }
  std::cout<<"connect success!"<<std::endl;

  //进行业务请求，开始通信
  while(true)
  {
    std::cout<<"Please Enter# ";
    char buffer[1024];
    fgets(buffer,sizeof(buffer)-1,stdin);
    write(sock,buffer,strlen(buffer));

    //信息返回
    ssize_t s = read(sock,buffer,sizeof(buffer)-1);
    if(s>0)
    {
      buffer[s]=0;
      std::cout<<"server echo# "<<buffer<<std::endl;
    }
  }
  return 0;
}
